package com.lst.demo.preview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class SaveNetPhotoUtils {

    private static Context contexts;
    private static String photoUrls;
    private static Bitmap bitmap;
    private static String mSaveMessage = "failed";


    /**
     * 保存图片，无须自定义名字
     *
     * @param context
     * @param photoUrl
     */
    public static void savePhoto(Context context, String photoUrl) {
        contexts = context;
        photoUrls = photoUrl;
        new Thread(saveFileRunnable).start();
    }


    private static Runnable saveFileRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (!TextUtils.isEmpty(photoUrls)) {
                    URL url = new URL(photoUrls);
                    InputStream inputStream = url.openStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    inputStream.close();
                }

                //保存图片到相册 DCIM/camera/
                 File file = ImageUtils.save2Album(bitmap, "lstdemo", Bitmap.CompressFormat.PNG);

                //保存到指定目录(需要通知图库进行更新,否则照片不会立即显示)
//                boolean save = ImageUtils.save(bitmap, PathUtils.getExternalStoragePath() + "/Pictures/" + System.currentTimeMillis() + ".png", Bitmap.CompressFormat.PNG);
//                LogUtils.i("保存:" + save);

                mSaveMessage = "图片已保存至 手机存储/Pictures 文件夹";
                // 通知图库更新
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 判断SDK版本是不是4.4或者高于4.4
//                    String[] paths = new String[]{file.getAbsolutePath()};
//                    MediaScannerConnection.scanFile(contexts, paths, null, null);
//                } else {
//                    final Intent intent;
//                    if (file.isDirectory()) {
//                        intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
//                        intent.setClassName("com.android.providers.media", "com.android.providers.media.MediaScannerReceiver");
//                        intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
//                    } else {
//                        intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//                        intent.setData(Uri.fromFile(file));
//                    }
//                    contexts.sendBroadcast(intent);
//                }

            } catch (IOException e) {
                mSaveMessage = "保存失败";
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }
    };


    /**
     * 保存成功和失败通知
     */
    @SuppressLint("HandlerLeak")
    private static Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //  Toast.makeText(contexts, mSaveMessage, Toast.LENGTH_LONG).show();
            ToastUtils.showLong(mSaveMessage);
        }
    };


}
